<template>
  <div class="import-modal modal" v-if="visible">
    <div class="import-component dialog">
      <header class="header">{{ title }}</header>
      <main class="main" v-loading="loading">
        <div class="body">
          <div class="error-msg-wrapper" v-if="errorMsg.length">
            <span>{{ errorMsg }}</span>
          </div>
          <div class="select-file">
            <input
              type="button"
              id="input-button"
              value="上传文件"
              @click="toSelectFile"
            />
            <input type="text" id="input-text" />
            <input
              type="file"
              id="input-file"
              style="display: none"
              @change="showFileName"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            />
          </div>
          <div class="template-wrapper" v-if="![5, 6].includes(type)">
            <a class="btn" :href="excelPath">模板下载</a>
          </div>
          <div class="template-wrapper" v-else>
            <span class="btn" @click="exportExcel">模板下载</span>
          </div>
        </div>
        <div class="footer">
          <div class="btn-group">
            <div class="cancel-btn btn" @click="cancel">取消</div>
            <div class="confirm-btn btn" @click="confirm">预览导入</div>
          </div>
        </div>
      </main>
    </div>

    <div class="import-preview dialog" v-show="step === 2">
      <header class="header" v-html="step2Title"></header>
      <main class="main" v-loading="loading">
        <div class="body">
          <div class="overview">
            <!-- 学生 -->
            <div class="row" v-if="type === 5">
              <div class="item">
                <span class="item-name">更新学生:</span>
                <span class="item-num update-num">{{
                  previewData.F_update_student_num
                }}</span>
              </div>
              <div class="item">
                <span class="item-name">新增班级:</span>
                <span class="item-num update-num">{{
                  previewData.F_create_class_num
                }}</span>
              </div>
            </div>
            <div class="row" v-if="[1, 2].includes(type)">
              <div class="item">
                <span class="item-name">新增学生:</span>
                <span class="item-num add-num">{{
                  previewData.F_create_student_num
                }}</span>
              </div>
              <div class="item">
                <span class="item-name">更新学生:</span>
                <span class="item-num update-num">{{
                  previewData.F_update_student_num
                }}</span>
              </div>
            </div>
            <!-- 老师、成员 -->
            <div class="row" v-if="[1, 3, 6, 4].includes(type)">
              <div class="item">
                <span class="item-name"
                  >新增{{ type === 4 ? '用户' : '老师' }}:</span
                >
                <span class="item-num add-num">{{
                  previewData.F_create_user_role_num
                }}</span>
              </div>
              <div class="item">
                <span class="item-name"
                  >更新{{ type === 4 ? '用户' : '老师' }}:</span
                >
                <span class="item-num update-num">{{
                  previewData.F_update_user_role_num
                }}</span>
              </div>
            </div>
            <!-- 班级 -->
            <div class="row" v-if="[1, 2, 3, 6].includes(type)">
              <div class="item">
                <span class="item-name">新增班级:</span>
                <span class="item-num add-num">{{
                  previewData.F_create_class_num
                }}</span>
              </div>
              <div class="item">
                <span class="item-name">更新班级:</span>
                <span class="item-num update-num">{{
                  previewData.F_update_class_num
                }}</span>
              </div>
            </div>
          </div>
          <div class="detail">
            <ul class="nav-list">
              <li
                class="btn"
                v-for="item in tabs"
                :key="item.id"
                :class="{ current: tab.id === item.id }"
                @click="tab = item"
              >
                {{ item.name }}
              </li>
            </ul>
            <div class="tables table-container">
              <div class="table-wrapper">
                <!-- 新增、更新 老师、角色 -->
                <el-table
                  v-if="[1, 2, 3, 4].includes(tab.id)"
                  :data="
                    [1, 3].includes(tab.id)
                      ? previewData.F_create_user_role_list || []
                      : previewData.F_update_user_role_list || []
                  "
                  class="responsive-table"
                >
                  <el-table-column
                    v-for="{ label, prop } in userColumnList"
                    align="center"
                    :key="prop"
                    :label="label"
                    :prop="prop"
                  ></el-table-column>
                </el-table>

                <!-- 年级科目负责人 -->
                <el-table
                  v-if="tab.id === 9"
                  :data="gradeSubjectInfoList"
                  class="responsive-table"
                >
                  <el-table-column
                    v-for="{ label, prop, width } in gradeSubjectColumnList"
                    align="center"
                    :prop="prop"
                    :key="prop"
                    :label="label"
                    :min-width="width"
                  >
                  </el-table-column>
                </el-table>

                <!-- 任课信息 -->
                <el-table
                  v-if="tab.id === 0"
                  :data="teachingInfoList"
                  class="responsive-table"
                >
                  <el-table-column
                    v-for="{ label, prop, width } in teachingColumnList"
                    align="center"
                    :prop="prop"
                    :key="prop"
                    :label="label"
                    :min-width="width"
                  >
                  </el-table-column>
                </el-table>

                <!-- 学生 -->
                <el-table
                  v-if="[5, 6].includes(tab.id)"
                  :data="
                    tab.id === 5
                      ? (previewData.F_create_student_list || [])
                      : (previewData.F_update_student_list || [])
                  "
                  class="responsive-table"
                >
                  <el-table-column
                    label="学号/考号"
                    prop="F_no"
                    align="center"
                    min-width="120px"
                  ></el-table-column>
                  <el-table-column
                    label="姓名"
                    prop="F_name"
                    align="center"
                    min-width="120px"
                  ></el-table-column>
                  <el-table-column label="班级" align="center" min-width="140px">
                    <template #default="scope">
                      {{
                        scope && scope.row
                          ? getClassName(
                              scope.row.F_grade_id,
                              scope.row.F_class_index
                            )
                          : ''
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column label="性别" align="center" min-width="70px">
                    <template #default="slot">
                      {{ slot && slot.row ? (['-', '男', '女'][slot.row.F_gender] || '-') : '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="学籍号"
                    prop="student_code"
                    align="center"
                    min-width="120px"
                  ></el-table-column>
                  <el-table-column
                    label="身份证号码"
                    prop="F_identity_number"
                    align="center"
                    min-width="175px"
                  ></el-table-column>
                  <el-table-column
                    label="考场"
                    prop="F_room_no"
                    align="center"
                    min-width="120px"
                  ></el-table-column>
                  <el-table-column
                    label="座位号"
                    prop="F_seat_no"
                    align="center"
                    min-width="120px"
                  ></el-table-column>
                  <el-table-column
                    label="选考科目"
                    align="center"
                    min-width="260px"
                    v-if="haveHighschoolStudent"
                  >
                    <template #default="scope">
                      {{ scope && scope.row ? getSubjectNameStr(scope.row.F_courses) : '' }}
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 班级 -->
                <el-table
                  v-if="tab.id === 7"
                  :data="previewData.F_create_class_list || []"
                  class="responsive-table"
                >
                  <el-table-column label="班级" align="center">
                    <template #default="slot">
                      {{ slot && slot.row ? slot.row : '' }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>

        <div class="footer">
          <div class="btn-group">
            <div class="cancel-btn btn" @click="cancel">取消</div>
            <div class="confirm-btn btn" @click="confirm">确认</div>
          </div>
        </div>
      </main>
    </div>

    <div class="import-preview error-dialog dialog" v-if="errorInfoList.length">
      <header class="header">导入提示</header>
      <div class="error-body">
        <div class="info">
          <template v-if="!showEmptyPhoneTip">
            <img src="@/assets/image/common/error.png" alt="" />
            <span>导入失败，请根据错误提示修改并重新上传。</span>
            <span class="blue download-btn" @click="toDownloadExcel"
              >下载错误报告</span
            >
          </template>
          <template v-else>
            <span>检测到表格中有以下行手机号为空，是否继续导入?</span>
          </template>
        </div>

        <div class="content">
          <div class="header">
            <div
              class="arrow-btn"
              @click="switchSheet(true)"
              :class="{ disable: currSheet.index === 0 }"
            >
              <i class="el-icon-caret-left"></i>
            </div>
            <div class="sheet-name-list" id="sheet-name-list">
              <div
                class="sheet-name"
                v-for="(sheet, index) in sheetList"
                :class="{ active: currSheet.index === index }"
                @click="currSheet = sheet"
              >
                表：{{ sheet.name }}
              </div>
            </div>
            <div
              class="arrow-btn"
              @click="switchSheet(false)"
              :class="{ disable: currSheet.index === sheetList.length - 1 }"
            >
              <i class="el-icon-caret-right"></i>
            </div>
          </div>
          <div class="table">
            <div class="import-table-header">
              <div class="row">
                <div class="cell">行序</div>
                <div class="cell" style="text-align: center">
                  {{ showEmptyPhoneTip ? '校验结果' : '错误原因' }}
                </div>
              </div>
            </div>
            <div class="table-body">
              <div
                class="row"
                v-for="{ err_msg, row_num } in sheetInfo.err_list"
                :key="row_num"
              >
                <div class="cell">{{ row_num }}</div>
                <div
                  class="cell"
                  style="display: block; text-align: left; line-height: 30px"
                >
                  {{ err_msg }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="tip" v-if="showEmptyPhoneTip">
          <span class="blue">*若继续导入，系统将自动生成虚拟号填充。</span>
        </div>
      </div>
      <div class="footer">
        <div class="btn-group">
          <div class="cancel-btn btn" @click="cancel">取消</div>
          <div
            class="confirm-btn btn"
            @click="confirm"
            v-if="showEmptyPhoneTip"
          >
            继续导入
          </div>
          <div class="confirm-btn btn" @click="goBack" v-else>重新上传</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { downloadExcelBlob } from '@/utils/utils';
import { getRandomCode } from '@/utils/utils';
import { USER_COLUMN_LIST } from '@/utils/constant';
export default {
  name: 'Import',
  data() {
    return {
      loading: false,
      errorMsg: '',
      errorInfoList: [],
      schoolId: '',
      excelFile: null,
      title: '导入Excel文件',
      step2Title: '导入结果预览',
      step: 1,
      visible: false,
      haveHighschoolStudent: false,
      inputText: null,
      inputFile: null,
      previewData: {},
      type: 1,
      tabs: [],
      tab: { id: -1, name: '' },
      randomCode: '',
      userColumnList: USER_COLUMN_LIST,
      teachingColumnList: [],
      teachingInfoList: [],

      currSheet: {},
      showEmptyPhoneTip: false,
      gradeSubjectInfoList: [],
      gradeSubjectColumnList: [],
    };
  },
  mounted() {
    this.randomCode = getRandomCode();
  },
  computed: {
    excelPath() {
      const { importType } = this.$maps;
      const templateMap = {
        [importType.TEACHER]: 'https://static.hhyunyue.com/website/helper/template/教师管理信息录入模板.xlsx',
        [importType.STUDENT]: 'https://static.hhyunyue.com/website/helper/template/学生信息录入模板 .xlsx',
        [importType.USER]: 'https://static.hhyunyue.com/website/helper/template/成员管理信息录入模板.xlsx'
      };
      return templateMap[this.type] + '?' + this.randomCode;
    },
    sheetList() {
      return this.errorInfoList.map((e, index) => ({
        index,
        name: e.sheet_name,
      }));
    },
    sheetInfo() {
      if (!this.errorInfoList.length) {
        return [];
      }
      return this.errorInfoList[this.currSheet.index];
    },
  },
  watch: {
    previewData() {
      if (this.previewData.F_class_teacher) {
        this.getTeachingInfo();
      }
      if (this.previewData.F_grade_subject) {
        this.getGradeSubjectInfo();
      }
      if (this.previewData.F_create_student_list) {
        const { F_create_student_list = [], F_update_student_list = [] } =
          this.previewData;
        this.haveHighschoolStudent = F_create_student_list.concat(
          F_update_student_list
        )
          .map((e) => e.F_grade_id)
          .some((e) => e >= 10);
      }
    },
    sheetList(v) {
      this.currSheet = this.sheetList[0];
    },
    visible() {
      if (this.visible === true) {
        this.$nextTick(() => {
          this.inputText = document.getElementById('input-text');
          this.inputFile = document.getElementById('input-file');
        });
      }
    },
  },
  methods: {
    async exportExcel() {
      this.loading = true;
      try {
        const api =
          this.type === this.$maps.importType.UPDATE_STUDENT
            ? this.$api.exportSchoolStudent
            : this.$api.exportSchoolTeacher;
        const fileName =
          this.type === this.$maps.importType.UPDATE_STUDENT
            ? '学生信息'
            : '教师信息';
        const res = await api({ F_school_id: this.schoolId });
        downloadExcelBlob(res, fileName);
      } catch (e) {
        console.error(e);
      }
      this.loading = false;
    },
    prevSheet() {
      const index = this.currSheet.index;
      if (index === 0) return;
      this.currSheet = this.sheetList[index - 1];
    },
    switchSheet(flag) {
      // true 左, false 右
      const index = this.currSheet.index;
      if (
        (index === 0 && flag) ||
        (index === this.sheetList.length - 1 && !flag)
      )
        return;
      const targetIndex = flag ? index - 1 : index + 1;

      const container = document.querySelector('#sheet-name-list');
      const element = document.querySelectorAll('.sheet-name')[targetIndex];
      const containerRect = container.getBoundingClientRect();
      const elementRect = element.getBoundingClientRect();

      // 判断元素左右边界是否在容器内
      if (
        !(
          elementRect.left >= containerRect.left &&
          elementRect.right <= containerRect.right
        )
      ) {
        element.scrollIntoView({ behavior: 'smooth' });
        // const scrollLeft = flag
        //   ? container.scrollLeft - element.offsetWidth
        //   : container.scrollLeft + element.offsetWidth;
        // container.scroll({ left: scrollLeft, behavior: 'smooth' });
      }

      this.currSheet = this.sheetList[targetIndex];
    },
    async toDownloadExcel() {
      const { importType } = this.$maps;
      const excelUrlMap = {
        [importType.SCHOOL]:
          '/v1/teaching/uc/schadm/schools/import/preview/user3/exportError',
        [importType.STUDENT]:
          '/v1/teaching/uc/schadm/schools/import/preview/user/student/new/exportError',
        [importType.UPDATE_STUDENT]:
          '/v1/teaching/uc/schadm/schools/import/preview/user/student2/new/exportError',
        [importType.TEACHER]:
          '/v1/teaching/uc/schadm/schools/import/preview/user/teacher/new/exportError',
        [importType.UPDATE_TEACHER]:
          '/v1/teaching/uc/schadm/schools/import/preview/user/teacher/new/exportError',
        [importType.USER]:
          '/v1/teaching/uc/schadm/schools/import/preview/user/role/new/exportError',
      };
      const url = excelUrlMap[this.type];
      const data = new FormData();
      data.append('F_school_id', this.schoolId);
      data.append('excel', this.excelFile);
      const res = await this.$api.exportErrorExcel(url, data);
      const name = this.excelFile.name.split('.xls')[0];
      downloadExcelBlob(res, name + '错误报告.xlsx');
    },
    goBack() {
      this.step = 1;
      this.errorInfoList = [];
      this.errorMsg = '';
    },
    getTeachingInfo() {
      const {
        F_class_teacher: { header, list },
      } = this.previewData;
      this.teachingColumnList = (header || []).map((e, index) => {
        return {
          label: e,
          prop: `column_${index}`,
          width: index === 0 ? '140px' : '100px',
        };
      });
      this.teachingInfoList = (list || []).map((classItem) => {
        const item = {};
        classItem.forEach((e, index) => {
          item[`column_${index}`] = e;
        });
        return item;
      });
    },
    getGradeSubjectInfo() {
      const {
        F_grade_subject: { header, list },
      } = this.previewData;
      this.gradeSubjectColumnList = (header || []).map((e, index) => {
        return {
          label: e,
          prop: `column_${index}`,
          width: '140px',
        };
      });
      this.gradeSubjectInfoList = (list || []).map((rowItem) => {
        const item = {};
        rowItem.forEach((e, index) => {
          item[`column_${index}`] = e;
        });
        return item;
      });
    },
    toSelectFile() {
      this.inputFile.click();
    },
    showFileName() {
      this.inputText.value = this.inputFile.value;
    },
    getClassName(gradeId, classIndex) {
      const { gradeList } = this.$maps;
      const gradeName = gradeList.find((e) => e.id === gradeId)?.name || '';
      return `${gradeName}（${classIndex}）班`;
    },
    getSubjectNameStr(coursesList) {
      coursesList = coursesList || [];
      const schoolSubjectList = this.__store.getters['school/schoolSubjectList'] || [];
      let list = schoolSubjectList.filter((e) =>
        coursesList.includes(e.id)
      );
      return list.length === 0
        ? ''
        : ['语文', '数学'].concat(list.map((e) => e.name)).join('、');
    },
    getTeachClassName(gradeId, classIndex, subjectId) {
      const { gradeList, subjectList } = this.$maps;
      const grade = gradeList.find((e) => e.id == gradeId);
      const subject = subjectList.find((e) => e.id == subjectId);
      return `${grade.name}（${classIndex}）班${subject.name}`;
    },
    cancel() {},
    confirm() {},
  },
};
</script>

<style lang="less" scoped>
.dialog {
  position: fixed;
  z-index: 996;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 6px;
  background-color: #fff;
  background-image: linear-gradient(#ffffff, #ffffff),
    linear-gradient(#cccccc, #cccccc);
  background-blend-mode: normal, normal;
  box-shadow: 0px 5px 30px 0px rgba(0, 0, 0, 0.15);
  color: #666;
  display: flex;
  flex-direction: column;
  .header {
    font-size: 18px;
    height: 54px;
    line-height: 54px;
    // font-weight: bold;
    background-color: #f4f4f4;
    border-radius: 6px 6px 0 0;
  }
  .body {
    box-sizing: border-box;
    padding: 15px 24px;
    flex: 1;
    text-align: start;
    overflow-y: auto;
    .error-msg-wrapper {
      padding-bottom: 10px;
    }
  }
  .footer {
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    .btn-group {
      display: flex;
      .btn {
        box-sizing: border-box;
        width: 85px;
        height: 35px;
        line-height: 35px;
      }
      .cancel-btn {
        color: #b3b3b3;
        background-color: #fff;
        border: solid 2px #f5f5f5;
        margin-right: 20px;
      }
      .confirm-btn {
        color: #fff;
        background-color: #009cff;
      }
    }
  }
}
.import-component {
  width: 600px;
  // height: 350px;
  .body {
    .select-file {
      margin-bottom: 20px;
      display: flex;
      #input-button {
        width: 111px;
        height: 40px;
        background-color: #009cff;
        color: #fff;
        cursor: pointer;
      }
      #input-text {
        display: inline-flex;
        flex-shrink: 1;
        box-sizing: border-box;
        width: 100%;
        height: 40px;
        border: 1px solid #e0e0e0;
        font-size: 16px;
        padding: 0 15px;
      }
    }
    .template-wrapper {
      .btn {
        color: #009cff;
        display: inline-block;
        text-decoration: none;
      }
    }
  }
}
.import-preview {
  z-index: 999;
  width: auto;
  width: 800px;
  height: 642px;
  .body {
    width: 100%;
    .overview {
      margin-bottom: 14px;
      .row {
        display: flex;
        .item {
          padding-right: 20px;
          .item-name,
          .item-num {
            margin-right: 6px;
          }
          .add-num {
            color: #00ae67;
          }
          .update-num {
            color: #fc0;
          }
          .delete-num {
            color: #f13100;
          }
        }
      }
    }

    .detail {
      width: 100%;
      .nav-list {
        background-color: #f4f4f4;
        li {
          display: inline-block;
          height: 40px;
          line-height: 40px;
          padding: 0 12px;
          text-align: center;
          &.current {
            color: #009cff;
            background-color: #ebf5ff;
          }
        }
      }
      .tables {
        width: 100%;
        height: 380px;
      }
    }
  }
}

.error-dialog {
  width: 600px !important;
  .tip {
    text-align: left;
    line-height: 30px;
  }
}

.error-body {
  ::-webkit-scrollbar {
    height: 0px !important;
  }
  box-sizing: border-box;
  height: calc(642px - 54px - 60px);
  padding: 0 36px;
  display: flex;
  flex-direction: column;
  color: rgba(0, 0, 0, 0.9);
  .info {
    height: 54px;
    img {
      margin-right: 4px;
    }
    display: flex;
    align-items: center;
    .download-btn {
      cursor: pointer;
      text-decoration: underline;
    }
  }
  .blue {
    color: #19b4f9;
  }
  .content {
    .header {
      height: 50px;
      display: flex;
      .arrow-btn {
        flex-shrink: 0;
        width: 25px;
        cursor: pointer;
        color: rgba(0, 0, 0, 0.6);
        &.disable {
          cursor: not-allowed;
          color: rgba(0, 0, 0, 0.2);
        }
      }
    }
    flex: 1;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    .sheet-name-list {
      height: 100%;
      background-color: rgba(243, 244, 249, 0.75);
      display: flex;
      flex-wrap: nowrap;
      overflow-x: auto;
      overflow-y: hidden;
      user-select: none;
      border-bottom: 1px solid #e4e7ed;
      .sheet-name {
        cursor: pointer;
        padding: 0 26px;
        flex-shrink: 0;
        display: inline-block;
        line-height: 50px;
        &.active {
          background-color: #e2e4ef;
        }
      }
    }
    .table {
      flex: 1;
      overflow-y: auto;
      display: flex;
      flex-direction: column;
      .import-table-header {
        background-color: rgba(243, 244, 249, 0.75);
      }
      .table-body {
        flex: 1;
        overflow-y: auto;
        color: rgba(0, 0, 0, 0.6);
      }
      .row {
        min-height: 50px;
        display: flex;
        border-bottom: 1px solid #e4e7ed;
        .cell {
          box-sizing: border-box;
          width: calc(100% - 93px);
          padding: 10px 16px;
          display: flex;
          justify-content: center;
          align-items: center;
          &:nth-child(1) {
            width: 93px;
          }
        }
      }
    }
  }
}
</style>
